import { ref, computed } from 'vue'
/**
 * 消息管理
 */
export interface Message {
  text: string
  sender: 'user' | 'assistant'
  thinking?: boolean
  thinkingText?: string
  thinkingInterval?: any
  _round: number
  isStreaming?: boolean
  modelName?: string
  imageList?: string[]
  __idx?: number
  status?: 'before' | 'think' | 'running' | 'completed' | 'error'
  createTime?: string
  contentIndex?: number
}

export function useMessageManager() {
  const messages = ref<Message[]>([])

  const messagesLength = computed(() => messages.value.length)

  const addMessage = (message: Omit<Message, '__idx'>): number => {
    const newMessage = { ...message, __idx: messages.value.length }
    messages.value.push(newMessage)
    return messages.value.length - 1
  }

  const updateMessage = (index: number, updates: Partial<Message>) => {
    if (index >= 0 && index < messages.value.length) {
      messages.value[index] = { ...messages.value[index], ...updates }
    }
  }

  const removeMessage = (index: number) => {
    if (index >= 0 && index < messages.value.length) {
      messages.value.splice(index, 1)
      // 重新计算__idx
      messages.value.forEach((msg, idx) => {
        msg.__idx = idx
      })
    }
  }

  const clearMessages = () => {
    messages.value = []
  }

  const removeCurrentRoundAIMessages = (roundId: number) => {
    const indices: number[] = []
    for (let i = messages.value.length - 1; i >= 0; i--) {
      if (messages.value[i].sender === 'assistant' && messages.value[i]._round === roundId) {
        indices.push(i)
      }
    }
    indices.forEach(idx => messages.value.splice(idx, 1))
    // 重新计算__idx
    messages.value.forEach((msg, idx) => {
      msg.__idx = idx
    })
  }

  const getAIMessageIndex = (roundId: number): number => {
    return messages.value.findIndex(
      msg => msg.sender === 'assistant' && msg._round === roundId && msg.isStreaming
    )
  }

  return {
    messages,
    messagesLength,
    addMessage,
    updateMessage,
    removeMessage,
    clearMessages,
    removeCurrentRoundAIMessages,
    getAIMessageIndex
  }
}
